<template>
  <div>
    <div class="amap">
      <div id="container" style="width: 100%; height: 100vh" />
      <div class="sidebar">
        <div class="leftbox">
          <!-- 树节点过滤 -->
          <div>
            <el-input
              placeholder="输入关键字进行过滤"
              size="small"
              v-model="filterText"
            >
            </el-input>
          </div>
          <!-- 树组件 -->
          <div style="margin-top: 15px">
            <el-tree
              ref="tree"
              :props="props"
              :highlight-current="true"
              @node-click="handleNodeClick"
              :filter-node-method="filterNode"
              :load="loadNode"
              lazy
            >
            </el-tree>
          </div>
        </div>
      </div>
    </div>
    <el-dialog
      :visible.sync="dialogVisible"
      width="1000px"
      v-if="dialogVisible"
      :close-on-click-modal="false"
      :destroy-on-close="true"
      :before-close="handleClose"
    >
      <CompanyInfo :companyInfo="companyInfo" />
    </el-dialog>
  </div>
</template>

<script>
import CompanyInfo from './CompanyInfo'
import AMapLoader from '@amap/amap-jsapi-loader'
import {
  getCompanyGLApi,
  getCompanyMsgApi,
  getCompanyInfoApi,
  getMapPointApi,
  getCompanyTreeApi
} from '@/api/powerFlow'
import { getLineTreeApi, getPointTreeApi } from '@/api/fileFlow'
import dayjs from 'dayjs'
window._AMapSecurityConfig = {
  // 安全密钥
  // securityJsCode: '98404c23880b42f03d5faaa96a51a4f4'
  securityJsCode: '495b13f555dfc1483f5ab78c453e6315'
}
export default {
  name: 'MyMapIndex',
  components: { CompanyInfo },
  data () {
    return {
      // 地图实例
      loca: null,
      map: null,
      pointLine: [],
      marker: null,
      form: {
        lng: '',
        lat: ''
      },
      dialogVisible: false,
      companyInfo: {},
      filterText: '',
      props: {
        label: 'name',
        children: 'sonList'
      }
    }
  },
  watch: {
    filterText (val) {
      this.$refs.tree.filter(val)
    }
  },
  mounted () {
    this.initMap()
    this.getMapPoint()
  },
  methods: {
    initMap () {
      AMapLoader.load({
        // key: '36726b83d3822ae3f31648d75d5f64a2', 
        key: '501062f563d27a055ca9c3debff4e31e', 
        version: '2.0', // 指定要加载的JSAPI的版本，缺省时默认为1.4.15
        plugins: [
          'AMap.Autocomplete',
          'AMap.PlaceSearch',
          'AMap.Scale',
          'AMap.OverView',
          'AMap.ToolBar',
          'AMap.MapType',
          'AMap.PolyEditor',
          'AMap.CircleEditor'
        ],
        Loca: {
          // 是否加载 Loca,缺省不加载
          version: '2.0.0' // Loca 版本,缺省1.3.2
        }
      }).then((AMap) => {
        this.map = new AMap.Map('container', {
          zoom: 5.2,
          center: [116.352734, 39.8447],
          mapStyle: 'amap://styles/grey',
          showLabel: true, // 不显示地名
          showBuildingBlock: true, // 显示建筑物
          viewMode: '3D' // 查看视野
        })

        const lineList = []
        for (const bdz of this.pointLine) {
          for (const line of bdz.sonList || []) {
            const poiList = []
            poiList.push([
              bdz.longitude,
              bdz.latitude,
              bdz.name,
              bdz.companyNo || ''
            ])
            for (const point of line.sonList || []) {
              poiList.push([
                point.longitude,
                point.latitude,
                point.name,
                point.companyNo || ''
              ])
            }
            lineList.push({ poiList, name: line.name })
          }
        }
        console.log(this.pointLine)
        console.log(lineList)
        lineList.forEach((item) => {
          const path = item.poiList.map((item) => item.slice(0, 2))
          console.log(path)
          const polyline = new AMap.Polyline({
            path: path, // 设置线覆盖物路径
            showDir: true,
            strokeColor: '#3366bb', // 线颜色
            strokeWeight: 10 // 线宽
          })
          const qiyeImg = require('@/assets/企业点.png')
          item.poiList.forEach((i) => {
            const marker = new AMap.Marker({
              position: new AMap.LngLat(i[0], i[1]),
              map: this.map,
              icon: new AMap.Icon({
                image: qiyeImg
              }),
              extData: { companyNo: i[3] }
            })

            marker.setLabel({
              direction: 'bottom',
              offset: new AMap.Pixel(-20, 0), // 设置文本标注偏移量
              content: `<div >${i[2]}</div>` // 设置文本标注内容
            })

            const infoWindow1 = new AMap.InfoWindow({
              isCustom: true,
              offset: new AMap.Pixel(0, -30)
            })
            const infoWindow2 = new AMap.InfoWindow({
              offset: new AMap.Pixel(0, -30)
            })
            marker.on('mouseover', async (e) => {
              if (!marker.getExtData().companyNo) return
              const {
                data: {
                  entity: { capacity, loadRate, power }
                }
              } = await getCompanyGLApi(marker.getExtData().companyNo)
              marker.content = `<ul class='infoWindow1' >
                            <li><span >功率：${power || '-'} kW</span></li>
                            <li><span >容量：${capacity || '-'} kVA</span></li>
                            <li><span >负载率：${loadRate || '-'} %</span></li>
                          </ul>`
              infoWindow1.setContent(e.target.content) // 自定义窗口添加一个盒子去展示对应Marker(地图上的图标)所要展示的信息
              infoWindow1.open(this.map, e.target.getPosition()) // Marker(地图上的图标)  打开自定义窗口的事件
            })
            marker.on('click', async (e) => {
              const companyNo = marker.getExtData().companyNo
              if (!companyNo) return
              const {
                data: {
                  entity: {
                    electricityNum,
                    inspectionTimes,
                    defectNum,
                    starLevel,
                    contractDate
                  }
                }
              } = await getCompanyMsgApi(companyNo)
              marker.content = `<ul class='infoWindow2' onclick='info()'>
                            <li><span >本年用电量：${electricityNum || '-'} kWh</span></li>
                            <li><span >本年巡视次数：${inspectionTimes || '-'} 次</span></li>
                            <li><span >本年缺陷个数：${defectNum || '-'} 个</span></li>
                            <li><span >星级：${starLevel || '-'} 星</span></li>
                            <li><span >合同日期：${contractDate || dayjs().format('YYYY-YY-DD')}</span></li>
                          </ul>`
              window.info = () => {
                this.info(companyNo)
              }
              infoWindow2.setContent(e.target.content) // 自定义窗口添加一个盒子去展示对应Marker(地图上的图标)所要展示的信息
              infoWindow2.open(this.map, e.target.getPosition()) // Marker(地图上的图标)  打开自定义窗口的事件
            })
            marker.on('mouseout', (e) => {
              infoWindow1.close()
            })
            this.map.add(marker)
            // 计算起点和终点的中心点作为文本覆盖物的位置
            if (path.length > 1) {
              const position = [
                (Number(path[0][0]) + Number(path[1][0])) / 2,
                (Number(path[0][1]) + Number(path[1][1])) / 2
              ]
              console.log(position)
              console.log(item)
              const text = new AMap.Text({
                text: `${item.name}`,
                position: position,
                offset: new AMap.Pixel(0, -30)
              })
              this.map.add(text)
            }
          })
          this.map.add([polyline])
        })
        const pointImg = require('@/assets/电源点.png')
        this.pointLine.forEach((item) => {
          const marker = new AMap.Marker({
            position: new AMap.LngLat(item.longitude, item.latitude),
            map: this.map,
            icon: new AMap.Icon({
              image: pointImg
            })
          })
          this.map.add(marker)
        })

        this.map.setFitView()
      })
    },
    removeMarker () {
      if (this.marker) {
        this.map.remove(this.marker)
      }
    },
    setMapMarker () {
      // 自动适应显示想显示的范围区域

      this.map?.setFitView()

      // eslint-disable-next-line no-undef
      this.marker = new AMap.Marker({
        map: this.map,
        position: [this.form.lng, this.form.lat]
      })

      this.map.add(this.marker)
      this.map?.setFitView()
    },
    async info (companyNo) {
      const res = await getCompanyInfoApi(companyNo)
      console.log(res.data.entity)
      this.companyInfo = res.data.entity
      this.dialogVisible = true
    },
    handleClose () {
      this.dialogVisible = false
    },
    async getMapPoint () {
      const res = await getMapPointApi()
      this.pointLine = res.data.list
      console.log(res)
    },
    async handleNodeClick (val) {
      if (val.type !== 3) {
        return
      }
      // console.log(val)
      // this.$set(this.form, 'lng', val.longitude)
      // this.$set(this.form, 'lat', val.latitude)
      // // 清除点
      // this.removeMarker()
      // // 标记点
      // this.setMapMarker()
      this.map.setCenter([val.longitude, val.latitude]) // 将指定的坐标设为地图中心点
      this.map.setZoom(16)
    },
    // 树节点过滤
    filterNode (value, data) {
      if (!value) return true
      return data.name.indexOf(value) !== -1
    },
    async loadNode (node, resolve) {
      if (node.level === 0) {
        // 初始的级数（最顶层）
        const res = await getPointTreeApi({ powerPointName: '', lineName: '' })
        // this.pointSelect = res.data.list
        console.log(res)
        return resolve(res?.data.list) // 最顶层数据渲染为region
      } else if (node.level === 1) {
        const res = await getLineTreeApi({
          powerPointId: node.data.originalId
        })
        this.lineList = res.data.list
        console.log(res)
        return resolve(res?.data.list)
      } else if (node.level === 2) {
        const res = await getCompanyTreeApi({ lineId: node.data.originalId })
        return resolve(res?.data.list)
      } else {
        return resolve([])
      }
    }
  },

  unmounted () {
    this.map?.destroy()
  }
}
</script>

<style lang="scss" scoped>
::v-deep.amap {
  position: relative;
  width: 100%;
  height: 100vh;
  .container {
    width: 100%;
    height: 100%;
  }
  .sidebar {
    position: absolute;
    width: 300px;
    height: 100%;
    top: 0;
    left: 0;
    background-color: rgba(255, 255, 255, 0.5);
    .leftbox {
      width: 300px;
      height: 100%;
      padding: 20px;
      .el-tree {
        background-color: rgba(255, 255, 255, 0);
      }
      .el-input__inner {
        background-color: rgba(255, 255, 255, 0.8);
      }
    }
  }
}

::v-deep .amap-logo {
  display: none !important;
  visibility: hidden !important;
}
::v-deep .amap-copyright {
  display: none !important;
  visibility: hidden !important;
}

::v-deep .amap-icon {
  position: relative;
  transform: translate(-50%, -50%);
}
::v-deep .amap-marker-label {
  border: none;
  color: #fff;
  font-size: 18px;
  background-color: rgba(255, 0, 0, 0);
}
::v-deep .amap-overlay-text-container {
  border: none;
  color: #fff;
  font-size: 14px;
  background-color: rgba(255, 0, 0, 0);
}
::v-deep .infoWindow1 {
  width: 160px;
  color: #fff;
  list-style-type: none;
  background-color: rgba(255, 255, 255, 0.5);
  padding: 10px;
}
::v-deep .infoWindow2 {
  width: 200px;
  color: #333;
  cursor: pointer;
}
::v-deep .el-dialog__body {
  padding: 0;
}
</style>
